package org.insist.best.codeGenerator.service;

import cn.hutool.core.io.IoUtil;
import cn.hutool.json.JSONObject;
import org.insist.best.codeGenerator.bo.GenerateCodeBo;
import org.insist.best.codeGenerator.core.DbConfig;
import org.insist.best.codeGenerator.core.GenerateUtil;
import org.insist.best.codeGenerator.dao.DataBaseInfoDao;
import org.insist.best.codeGenerator.dao.DataBaseInfoDaoFactory;
import org.insist.best.codeGenerator.vo.ColumnListItem;
import org.insist.best.codeGenerator.vo.TableListItem;
import org.springframework.stereotype.Service;

import java.io.ByteArrayOutputStream;
import java.util.List;
import java.util.zip.ZipOutputStream;


@Service
public class GeneratorService {

    public JSONObject queryList(DbConfig dbConfig, String queryTableName, int page, int pageSize) {
        DataBaseInfoDao dataBaseInfoDao = DataBaseInfoDaoFactory.getDataBaseDao(dbConfig);
        return dataBaseInfoDao.queryList(queryTableName, page, pageSize);
    }


    public byte[] generateCode(GenerateCodeBo codeBo) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        ZipOutputStream zip = new ZipOutputStream(outputStream);
        DataBaseInfoDao dataBaseInfoDao = DataBaseInfoDaoFactory.getDataBaseDao(codeBo.getQueryBo().toDbConfig());
        for (String tableName : codeBo.getTableNames()) {
            TableListItem tableListItem = dataBaseInfoDao.queryTable(tableName);
            List<ColumnListItem> columnListItems = dataBaseInfoDao.queryColumns(tableName);

            GenerateUtil.generateCode(tableListItem, columnListItems, zip, codeBo.getGenerateConfig());
        }

        IoUtil.close(zip);
        return  outputStream.toByteArray();
    }
}
